package com.cfpamf.ms.insur.wx.request;


import com.cfpamf.ms.insur.wx.model.WxDownloadBillModel;
import com.cfpamf.ms.insur.wx.response.WxPayDownloadBillResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jodd.io.ZipUtil;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Consumer;
import java.util.zip.ZipException;

/**
 * 微信统一下单接口
 */
@Slf4j
public class WxPayDownloadBillRequest extends
        WxAbstractRequest<WxDownloadBillModel, WxPayDownloadBillResponse>
        implements WechatPayDownloadRequest<WxDownloadBillModel, WxPayDownloadBillResponse> {

    /**
     * 分页消费响应  如果不为空 则返回的resp会无效
     */
    private Consumer<WxPayDownloadBillResponse> consumer;

    public WxPayDownloadBillRequest(WxDownloadBillModel model) {
        super(model);
    }

    public WxPayDownloadBillRequest(WxDownloadBillModel model, Consumer<WxPayDownloadBillResponse> consumer) {
        this(model);
        this.consumer = consumer;

    }

    @Override
    public String getApiAction() {
        return "/pay/downloadbill";
    }

    @Override
    public Class<WxDownloadBillModel> getObjectClass() {
        return WxDownloadBillModel.class;
    }

    @Override
    public Class<WxPayDownloadBillResponse> getResponseClass() {
        return WxPayDownloadBillResponse.class;
    }

    @Override
    public boolean requireCert() {
        return true;
    }

    @Override
    public ResponseHandler<WxPayDownloadBillResponse> getResponseHandler(ObjectMapper mapper) {
        return response -> {

            HttpEntity entity = response.getEntity();

            //如果是xml就是访问有问题 如果是gizp说明成功了 应该可以
            Header contentType = entity.getContentType();
            String value = contentType.getValue();
            WxPayDownloadBillResponse result = new WxPayDownloadBillResponse();
            //如果返回的是gzip 就是正常数据
            if (value.contains("x-gzip")) {
                Path tempDirectory = Files.createTempDirectory("bill");
                Path path = Paths.get(tempDirectory.toString(), "bill" + System.currentTimeMillis() + ".gzip");
                Files.copy(entity.getContent(), path);
                try {
                    //分页处理
                    if (consumer != null) {
                        Path unzipFile = ZipUtil.ungzip(path.toFile()).toPath();
//                        Files.copy(unzipFile, new File("test.csv").toPath());
                        @Cleanup BufferedReader reader = Files.newBufferedReader(unzipFile);
                        WxPayDownloadBillResponse.parsePage(reader, consumer);
                    } else {
                        List<String> allLines = Files.readAllLines(ZipUtil.ungzip(path.toFile()).toPath(), StandardCharsets.UTF_8);
                        WxPayDownloadBillResponse.parse(allLines, result);
                    }
                    result.setReturnCode("SUCCESS");
                    result.setResultCode("SUCCESS");
                    result.setEnd(true);
                } catch (ZipException ze) {
                    // 解析失败的时候
                    log.warn("下载资金账单失败,", ze);
                }
            } else {
                //返回的是xml代表下载失败
                String respBody = EntityUtils.toString(entity);
                log.warn("下载资金账单失败==》{}", respBody);
                result = mapper.readValue(respBody, WxPayDownloadBillResponse.class);
            }
            return result;
        };
    }
}
